package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.model.Board;
import com.example.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 板块 controller 层
 * User: DELL
 * Date: 2023-09-21
 * Time: 21:07
 */
@Api(tags = "板块接口")
@Slf4j
@RestController
@RequestMapping("/board")
public class BoardController {

    // 从配置文件中读取首页中板块的数量,如果没有找到,则为默认值 9
    @Value("${bit-forum.index.board-num:9}")
    private Integer indexBoardNum;

    @Resource
    private IBoardService boardService;

    /**
     * 查询首页板块列表
     *
     * @return
     */
    @ApiOperation("获取首页板块列表")
    @GetMapping("/top-board")
    public AppResult topBoard() {
        // 调用 service 层方法
        List<Board> boards = boardService.selectTopNBoard(indexBoardNum);
        // 检验 boards 否为空
        if (boards == null) {
            boards = new ArrayList<>();
            // 打印日志
            log.warn("查询首页板块列表异常");
        }
        // 返回结果
        return AppResult.success(boards);
    }

    /**
     * 根据板块 id 获取对应板块信息
     *
     * @param id 板块id
     * @return
     */
    @ApiOperation("获取板块信息")
    @GetMapping("/getById")
    public AppResult getById(@ApiParam("板块id") @RequestParam("id") @NonNull Long id) {
        // 调用 service
        Board board = boardService.selectById(id);
        // 校验
        if (board == null || board.getDeleteState() != 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            // 返回结果
            return AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }
        // 返回结果
        return AppResult.success(board);
    }
}
